import {
  Form,
  Input,
  message,
  Row,
  Col,
  Select,
  Tabs,
  Table,
  Button,
} from 'antd';

import { withPropsAPI } from 'gg-editor';
import React, { useState } from 'react';
import {
  serviceNameByAppId,
  methodNameByServiceName,
} from '../api/ChoreographyMachine';
// import { versionByMethodName } from '../api/ChoreographyMachine/versionByMethodName';
import Modal from 'antd/lib/modal/Modal';
let lastSelectedItem;

const child = () => {};
const { Column, ColumnGroup } = Table;
const { TabPane } = Tabs;

class ServiceTaskNode extends React.Component {
  get item() {
    const { propsAPI } = this.props;
    return propsAPI.getSelected()[0]
      ? propsAPI.getSelected()[0]
      : lastSelectedItem;
  }

  constructor(props) {
    super(props);
    this.state = {
      setInputJson: '', // input框JSON数据
      setOutputJson: '', // output框JSON数据
      inputTable: [], // input 表格数据
      isAddInput: false, // input添加模态框是否显示
      outputTable: [], // output 表格数据
      isAddOutput: false, // output添加模态框是否显示
      appId: '', // 选择的ID
      serviceNameValue: '', // 选择的服务名称
      methodNameValue: '', // 选择的方法名称
      versionValue: '', // 选择的版本号
      serviceNameSelectDisabled: true, // 是否隐藏服务名选择
      ServiceOption: [], // 筛选后的服务名
      methodNameSelectDisabled: true, // 是否隐藏方法名选择
      MethodOption: [], // 筛选后的方法名
      versionSelectDisabled: false, // 是否隐藏版本选择
      versionOption: [], // 筛选后的版本号
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    const model = this.props.propsAPI.getSelected()[0].getModel();
    // console.log(model.stateProps);
  }

  // 改变版本号输入框后调用子组件刷新方法
  onRef = (ref) => {
    this.child = ref;
  };

  // 改变视图JSON数据，供父组件调用的方法
  changeFlowData = (e) => {
    if (e && e.preventDefault) {
      e.preventDefault();
    }
    // 获取当前的服务节点
    const item = this.item;
    // 从API中获取更新视图JSON数据的方法
    const { executeCommand, update } = this.props.propsAPI;
    const newItem = JSON.parse(JSON.stringify(item.model));

    const form = this.formRef.current.getFieldsValue();
    // console.log(form);
    newItem.stateProps.Input.ServiceName = this.state.serviceNameValue;
    newItem.stateProps.Input.ServiceMethod = this.state.methodNameValue;
    newItem.stateProps.appId = this.state.appId;
    newItem.stateProps.Status = { Status: form.Status };
    newItem.stateProps.Retry = { Retry: form.Retry };
    newItem.stateProps.Input.param = this.state.setInputJson;
    newItem.stateProps.Output = this.state.setOutputJson;
    // console.log('父组件提交了表单数据');
    executeCommand(() => {
      update(item.id, newItem);
    });
  };

  // form表单实例
  formRef = React.createRef();
  addInputRef = React.createRef();
  addOutputRef = React.createRef();

  getValues = () => {
    // 得到 Form 实例
    const form = this.formRef.current;
    // console.log(form);
    // 使用 getFieldsValue 获取多个字段值
    const values = form.getFieldsValue(['Input']);
    // console.log(values);
  };

  render() {
    const { Option } = Select;
    // 获取原表单数据
    var formDefaultValue = {
      Id:
        this.props.propsAPI.getSelected()[0].getModel().stateProps.appId || '',
      Input:
        this.props.propsAPI.getSelected()[0].getModel().stateProps.Input[0]
          ?.param?.count || '',
      Output:
        this.props.propsAPI.getSelected()[0].getModel().stateProps.Output
          ?.reduceInventoryResult || '',
      Status:
        this.props.propsAPI.getSelected()[0].getModel().stateProps.Status
          ?.Status || '',
      Retry:
        this.props.propsAPI.getSelected()[0].getModel().stateProps.Retry[0]
          ?.Retry || '',
    };
    // console.log(formDefaultValue);
    // console.log(
    //   this.props.propsAPI.getSelected()[0].getModel().stateProps.Input[0]
    //     ?.param,
    // );

    // 根据id获取服务名
    const serviceIdInput = () => {
      const form = this.formRef.current.getFieldsValue();
      const serviceId = form.ID;
      this.setState({
        appId: serviceId,
      });
      // 参数
      const serviceParm = {
        appId: serviceId,
      };
      serviceNameByAppId(serviceParm).then((val) => {
        const ServiceArray = [];
        for (let i = 0; i < val.data.length; i++) {
          ServiceArray.push(
            <Option key={i} value={val.data[i].serviceName}>
              {val.data[i].serviceName}
            </Option>,
          );
        }
        // 是否存在服务
        if (val.data[0]) {
          this.setState({
            serviceNameSelectDisabled: false,
          });
        } else {
          this.setState({
            serviceNameSelectDisabled: true,
            methodNameSelectDisabled: true,
            versionSelectDisabled: true,
          });
        }
        // 渲染服务名下拉框
        this.setState({
          ServiceOption: ServiceArray,
        });
      });
    };

    // 根据服务名获取方法名
    const serviceChange = (val) => {
      this.setState({
        serviceNameValue: val,
      });
      // console.log(val);
      const methodParm = {
        serviceName: val,
      };
      methodNameByServiceName(methodParm).then((val) => {
        const methodArray = [];
        for (let i = 0; i < val.data.length; i++) {
          methodArray.push(
            <Option key={i} value={val.data[i].methodName}>
              {val.data[i].methodName}
            </Option>,
          );
        }
        // 是否存在方法
        if (val.data[0]) {
          this.setState({
            methodNameSelectDisabled: false,
          });
        } else {
          this.setState({
            methodNameSelectDisabled: true,
            versionSelectDisabled: true,
          });
        }
        // 渲染方法名下拉框
        this.setState({
          MethodOption: methodArray,
        });
      });
    };

    /**
     *  @description 暂无
     */

    // 根据方法名获取版本
    const methodChange = (val) => {
      this.setState({
        methodNameValue: val,
      });
      // console.log(val);

      const versionParm = {
        methodName: val,
      };

      // versionByMethodName(versionParm).then(val => {
      //   const versionArray = [];
      //   for (let i = 0; i < val.data.length; i++) {
      //     versionArray.push(
      //       <Option key={i} value={val.data[i].serviceName}>
      //         {val.data[i].serviceName}
      //       </Option>,
      //     );
      //   }
      //   if (val.data[0]) {
      //     this.setState({
      //       versionNameSelectDisabled: false,
      //     });
      //   } else {
      //     this.setState({
      //       versionNameSelectDisabled: true,
      //       versionSelectDisabled: true
      //     });
      //   }
      //   this.setState({
      //     versionOption: versionArray,
      //   });

      // })
    };

    // 版本号改变回调
    const versionChange = (val) => {
      this.setState({
        versionValue: val,
      });
      // console.log(val);
    };

    // 增加Input 按钮点击事件
    const addInput = () => {
      this.setState({
        isAddInput: true,
      });
    };
    var inputBusJson = '';

    // 增加Input确认按钮
    const addInputOk = () => {
      try {
        const validate = this.addInputRef.current.validateFields();
        // 获取输入的键值对
        const addInputValue = this.addInputRef.current.getFieldsValue();
        // 拼接JSON字符串
        const addInputJSON =
          '{"' + addInputValue.key + '":"' + addInputValue.value + '"}';
        try {
          JSON.parse(addInputJSON);
        } catch (error) {
          message.info('请勿输入字符： "');
        }
        // 中转JSON
        var bus = [];
        // 获取已输入的键值对
        this.state.inputTable.forEach((val) => {
          bus.push(val);
        });
        // 添加刚输入的键值对
        bus.push({
          key: addInputValue.key,
          value: addInputValue.value,
        });
        // 更新键值对存储
        this.setState({
          inputTable: bus,
        });
        this.setState({
          isAddInput: false,
        });
        // 拼接JSON
        bus.forEach((val) => {
          // console.log(val);
          const inputJson = '"' + val.key + '":"' + val.value + '",';
          inputBusJson += inputJson;
        });
        // 将拼接好的JSON存储
        this.setState({
          setInputJson: JSON.parse(
            '{' + inputBusJson.substring(0, inputBusJson.length - 1) + '}',
          ),
        });
        setTimeout(() => {
          // console.log(this.state.setInputJson);
        }, 1);
        this.addInputRef.current.resetFields();
      } catch {}
    };

    // 增加Output 按钮点击事件
    const addOutput = () => {
      this.setState({
        isAddOutput: true,
      });
    };
    var outputBusJson = '';

    // 增加Output确认按钮

    const addOutputOk = () => {
      try {
        const validate = this.addOutputRef.current.validateFields();
        // 获取输入的键值对
        const addOutputValue = this.addOutputRef.current.getFieldsValue();
        // 拼接JSON字符串
        const addInputJSON =
          '{"' + addOutputValue.key + '":"' + addOutputValue.value + '"}';
        try {
          JSON.parse(addInputJSON);
        } catch (error) {
          message.info('请勿输入字符： "');
        }
        // 中转JSON
        var bus = [];
        // 获取已输入的键值对
        this.state.outputTable.forEach((val) => {
          bus.push(val);
        });
        // 添加刚输入的键值对
        bus.push({
          key: addOutputValue.key,
          value: addOutputValue.value,
        });
        // 更新键值对存储
        this.setState({
          outputTable: bus,
        });
        this.setState({
          isAddOutput: false,
        });
        // 拼接JSON
        bus.forEach((val) => {
          // console.log(val);
          const outputJson = '"' + val.key + '":"' + val.value + '",';
          outputBusJson += outputJson;
        });
        // 将拼接好的JSON存储
        this.setState({
          setOutputJson: JSON.parse(
            '{' + outputBusJson.substring(0, outputBusJson.length - 1) + '}',
          ),
        });
        setTimeout(() => {
          // console.log(this.state.setOutputJson);
        }, 1);
        this.addOutputRef.current.resetFields();
      } catch (err) {}
    };

    return (
      <div>
        <Form
          ref={this.formRef}
          name="ServiceTaskNodeForm"
          initialValues={formDefaultValue}
          layout="vertical"
        >
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item
                label="应用ID"
                name="ID"
                rules={[{ required: true, message: '请输入应用ID' }]}
                initialValue={formDefaultValue.Id}
              >
                <Input onChange={serviceIdInput} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                label="服务名"
                name="serviceName"
                rules={[{ required: true, message: '请选择服务名' }]}
              >
                <Select
                  showSearch
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  onChange={serviceChange}
                  disabled={this.state.serviceNameSelectDisabled}
                  value={this.state.serviceNameValue}
                >
                  {this.state.ServiceOption}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                label="方法名"
                name="methodName"
                rules={[{ required: true, message: '请选择方法名' }]}
              >
                <Select
                  showSearch
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  onChange={methodChange}
                  disabled={this.state.methodNameSelectDisabled}
                >
                  {this.state.MethodOption}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                label="版本号"
                name="version"
                rules={[{ required: true, message: '请选择版本号' }]}
              >
                <Select
                  showSearch
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  onChange={versionChange}
                  disabled={this.state.versionSelectDisabled}
                >
                  {this.state.versionOption}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                label="Status"
                name="Status"
                rules={[{ required: true, message: '请输入Status' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                label="Retry"
                name="Retry"
                rules={[{ required: true, message: '请输入Retry' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Tabs defaultActiveKey="1">
          <TabPane tab="系统报文" key="1">
            <Button onClick={addInput}> 添加Input键值对</Button>
            <Table
              scroll={{ x: 300 }}
              pagination={false}
              dataSource={this.state.inputTable}
            >
              <Column title="key" dataIndex="key" key="key" />
              <Column title="value" dataIndex="value" key="value" />
            </Table>
          </TabPane>
          <TabPane tab="响应报文" key="2">
            <Button onClick={addOutput}> 添加Output键值对</Button>
            <Table
              scroll={{ x: 300 }}
              pagination={false}
              dataSource={this.state.outputTable}
            >
              <Column title="key" dataIndex="key" key="key" />
              <Column title="value" dataIndex="value" key="value" />
            </Table>
          </TabPane>
        </Tabs>
        <Modal
          className="addInputModal"
          cancelText="取消"
          okText="确认"
          title="添加系统报文"
          visible={this.state.isAddInput}
          onOk={addInputOk}
          onCancel={() => {
            this.setState({
              isAddInput: false,
            });
          }}
        >
          <Form ref={this.addInputRef} size="middle" layout="vertical">
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  label="key"
                  name="key"
                  initialValues={this.state.addInputValueKey}
                  rules={[{ required: true }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="value"
                  name="value"
                  initialValues={this.state.addOutputValueValue}
                  rules={[{ required: true }]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
        <Modal
          className="addOutputModal"
          cancelText="取消"
          okText="确认"
          title="添加响应报文"
          visible={this.state.isAddOutput}
          onOk={addOutputOk}
          onCancel={() => {
            this.setState({
              isAddOutput: false,
            });
          }}
        >
          <Form ref={this.addOutputRef} size="middle" layout="vertical">
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  label="key"
                  name="key"
                  initialValues={this.state.addOutputValueKey}
                  rules={[{ required: true }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="value"
                  name="value"
                  initialValues={this.state.addOutputValueValue}
                  rules={[{ required: true }]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
      </div>
    );
  }
}
export default withPropsAPI(ServiceTaskNode);
